package com.zhonghan.recharge.controller;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.github.pagehelper.PageInfo;
import com.zhonghan.common.bean.Result;
import com.zhonghan.common.utils.ExcelUtils;
import com.zhonghan.recharge.pojo.ZhBusinessUser;
import com.zhonghan.recharge.pojo.ZhGascardOrder;
import com.zhonghan.recharge.service.BusinessRechargeService;
import com.zhonghan.recharge.service.ZhBusinessGascardOrderService;
import com.zhonghan.recharge.service.ZhBusinessUserService;


/**
 * 充值
 * @author zhangceven
 *
 */
@Controller
@RequestMapping("/business")
public class BusinessRechargeController {
	

	private Logger logger = Logger.getLogger(BusinessRechargeController.class);
	
	@Autowired
	private ZhBusinessGascardOrderService zhBusinessGascardOrderService;

	@Autowired
	private BusinessRechargeService businessRechargeService;
	@Autowired
	private ZhBusinessUserService zhBusinessUserService;
	
	
	/**
	 * 
	 * @param request
	 * @param gasType
	 * @param cards
	 * @param prices
	 * @return
	 */
	@RequestMapping("/recharges")
	@ResponseBody
	public Result recharges(HttpServletRequest request,String gasType,String cards,Integer prices,RedirectAttributes model) {
		Result result = new Result();
		HttpSession session = request.getSession();
		ZhBusinessUser user = (ZhBusinessUser) session.getAttribute("zhonghan_business_user");
		StringBuilder failedCards = new StringBuilder();
		if(user != null) {
			String[] _cards = cards.split(",");
			if(_cards != null && _cards.length>0 && _cards.length <= 100) {
				ZhBusinessUser businessUser = zhBusinessUserService.selectZhBusinessUserById(user.getId());
				Integer totalPrice = _cards.length * prices;
				if(businessUser.getTotalAssets() >= totalPrice) {
					int failedNum = 0;
					for (String cardnum : _cards) {
						result = businessRechargeService.insertOilRechargeServiceFromGasnumber(businessUser,cardnum, gasType, prices,user.getPortAppkey(),user.getPortAppsecret());
						if("0".equals(result.getCode())) {
							failedNum++;
							failedCards.append(result.getData()+";");
						}
					}
					//充值完成，
					if(failedNum>=0) {
						//充值成功，但有失败的
						result.setCode("2");
					}else {
						result.setCode("1");
					}
					result.setData(failedCards.toString());
					result.setMsg("充值完成");
				}else {
					//金额不够
					result.setCode("0");
					result.setMsg("你的金额不足");
				}
			}else {
				//没有充油卡
				result.setCode("0");
				result.setMsg("油卡信息错误");
			}
			
			
		}else {
			//登录
			result.setCode("0");
			result.setMsg("对不起，没有登录");
		}
		//model.addFlashAttribute("resultInfo", JSON.toJSONString(result));
		return result;
		//重定向
		//return "redirect:/business/recharges/result";
	}
	

	/**
	 * 充值结果
	 * @param request
	 * @param result
	 * @param model
	 * @return
	 */
	@RequestMapping("/recharges/result")
	public String rechargeSuccess(HttpServletRequest request,
			@ModelAttribute("resultInfo") String result, Model model) {
		
		model.addAttribute("msg", result);  
		
		return "business/recharge_result";
	}
	/**
	 *  跳转到充值界面
	 * @return
	 */
	@RequestMapping(value="/recharge/oil",method=RequestMethod.GET)
	public String showRecharge(){
		
		return "recharge";
	}
	
	/**
	 * 油卡充值
	 * @param card_type 油卡类型
	 * @param cards 卡号集合
	 * @param prices 金额
	 * @return
	 */
	@RequestMapping(value="/recharge/oil",method=RequestMethod.POST)
	public String toRecharge(String card_type,String cards,String prices ){
		
		
		return "";
	}
	
	/**
	 * 跳转至商户订单查询页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/order/get",method=RequestMethod.GET)
	public String showBusinessOrder(HttpServletRequest request, HttpServletResponse response){
		
		return "business/order";
	}
	
	/**
	 * 跳转至商户订单查询页面
	 * @param request
	 * @param response
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value="/order/get",method=RequestMethod.POST)
	@ResponseBody
	public Result getBusinessOrder(HttpServletRequest request, HttpServletResponse response, String orderNo, String gascardNo,
			String telephone, String fillCardSequence, String rechargeState, String beginTime, String endTime,
			String orderType, Integer pageNum, Integer pageSize) {
		
		pageSize = pageSize == null ? 10 : pageSize;
		ZhBusinessUser user = (ZhBusinessUser) request.getSession().getAttribute("zhonghan_business_user");
		
		Result result = zhBusinessGascardOrderService.selectZhBusinessGascardOrderByCondition(user.getId(),orderNo, gascardNo, telephone, fillCardSequence, rechargeState, beginTime, endTime, orderType, pageNum, pageSize);
		
		return result;
	}
	
	/**
	 * 导出订单表
	 * 
	 * @param request
	 * @param response
	 * @param orderNo
	 * @param gascardNo
	 * @param telephone
	 * @param fillCardSequence
	 * @param rechargeState
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/order/export")
	public void exportBusinessOrder(HttpServletRequest request, HttpServletResponse response, String orderNo, String gascardNo,
			String telephone, String fillCardSequence, String rechargeState, String beginTime, String endTime,
			String orderType) {
		ZhBusinessUser user = (ZhBusinessUser) request.getSession().getAttribute("zhonghan_business_user");
		Result result = zhBusinessGascardOrderService.selectZhBusinessGascardOrderByCondition(user.getId(),orderNo, gascardNo, telephone,
				fillCardSequence, rechargeState, beginTime, endTime, orderType, 0, 0);
		PageInfo<ZhGascardOrder> pageInfo = null;
		if (result != null) {
			pageInfo = (PageInfo<ZhGascardOrder>) result.getData();
		}
		List<ZhGascardOrder> list = pageInfo.getList();

		String[] headerColumns = { "orderNo", "fillCardSequence", "gascardNo", "bmItemName",
				"facePrice", "orderTime", "rechargeState" };
		String[] titleName = { "订单编号", "充值卡卡号", "油卡卡号", "商品名称", "面额", "时间", "订单状态" };

		ExcelUtils e = new ExcelUtils(request, response,
				"订单明细表" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()), "订单明细");
		e.setTitle("订单明细", 7);
		e.setHeader(titleName);
		e.export(headerColumns, list);
		
		logger.info("订单导出成功!");
	}
	
	/**
	 * 查询订单详情
	 * 
	 * @param request
	 * @param response
	 * @param orderNo
	 * @return
	 */
	@RequestMapping("/order/detail")
	@ResponseBody
	public Result getOrderDetail(HttpServletRequest request, HttpServletResponse response, String orderNo) {

		Result result = zhBusinessGascardOrderService.getOrderDetail(orderNo);

		return result;
	}
	
}
